//app.js
import network from './utils/network.js'
App({

  login:function(){
    let that = this;
    wx.getSetting({
      success: function (res) {
        console.log("options1")
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          // // 登录
          console.log("options2")
          wx.login({
            success: res => {
              // 发送 res.code 到后台换取 openId, sessionKey, unionId
              if (res.code) {
                let code = res.code
                wx.getUserInfo({
                  success: function (res) {
                    network.post({
                      url: 'auth/login', data: {
                        code: code,
                        encryptedData: res.encryptedData,
                        iv: res.iv
                      }
                    })
                      .then(({ code, data }) => {
                        if (code == 0) {
                          console.log(data)
                          that.globalData.userInfo = data.userInfo
                          that.globalData.token = data.token
                          wx.setStorageSync('token', data.token)
                          wx.setStorageSync('userId', data.userInfo.uid)
                          console.log(data.token)
                          console.log("gooooooooood999")
                          if (that.userCallBack) {
                            console.log("gooooooooood777")
                            that.userCallBack(data.userInfo)
                          }
                        } else {
                          if (that.userLoginCallBack) {
                            that.userLoginCallBack()
                          }
                        }

                      })
                  }
                })

              }
            }
          })

        }
      }
    })
  },
  onLaunch: function () {
    
    this.login()
    
  },
  globalData: {
    token: null,
    userInfo:null,  
  }
})